package com.jfl.web.controller.system;

import java.util.List;

import org.apache.curator.shaded.com.google.common.collect.Lists;
import org.apache.curator.shaded.com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.jfl.annotation.Log;
import com.jfl.base.AbstractController;
import com.jfl.common.Constants;
import com.jfl.core.utils.ShiroUtils;
import com.jfl.enums.LogType;
import com.jfl.enums.Module;
import com.jfl.exception.BusinessException;
import com.jfl.model.SysUser;
import com.jfl.system.SysDeptService;
import com.jfl.system.SysPostService;
import com.jfl.system.SysRoleService;
import com.jfl.system.SysUserService;
import com.jfl.utils.ConvertRequestUtil;
import com.jfl.utils.EncryptUtils;

/**
 * 用户管理
 * 
 * @author 赵炎
 * @version [V1.00, 2018年11月30日]
 * @since V1.00
 */
@Controller
@RequestMapping("${jfl.module.system}/user")
public class SysUserController extends AbstractController
{
    /**
     * dubbo接口 @Reference 通过配置文件连接服务
     */
    @Reference(version = "${jfl.version}")
    private SysUserService sysUserService;
    
    @Reference(version = "${jfl.version}")
    private SysDeptService sysDeptService;
    
    @Reference(version = "${jfl.version}")
    private SysRoleService sysRoleService;
    
    @Reference(version = "${jfl.version}")
    private SysPostService sysPostService;
    
    /**
     * 分隔符
     */
    private static final String SEG_CHAR = ",";
    /**
     * 用户管理界面
     * 
     * @param modelMap
     * @return
     */
    @RequiresPermissions("system:user:view")
    @GetMapping
    public String user(ModelMap modelMap)
    {
        modelMap.put("user", ShiroUtils.getCurrentUser());
        return Constants.MODULE_SYS_USER_PREFIX + "user";
    }
    
    /**
     * 跳转用户添加页面
     * 
     * @param modelMap
     * @return
     */
    @GetMapping("/add")
    public String add(ModelMap modelMap)
    {
        modelMap.put("roles", this.sysRoleService.queryList(Maps.newHashMap()));
        modelMap.put("posts", this.sysPostService.queryList(Maps.newHashMap()));
        return Constants.MODULE_SYS_USER_PREFIX + "add";
    }
    
    /**
     * 添加用户
     * 
     * @param user
     * @return
     */
    @Log(module = Module.ROLE, value = "添加用户", type = LogType.INSERT)
    @RequiresPermissions("system:user:add")
    @PostMapping("/add")
    @ResponseBody
    public ResponseEntity<ModelMap> addSave(SysUser user)
    {
        user.setSalt(EncryptUtils.randomSalt());
        user.setPassword(EncryptUtils.encryptPassword(user.getUserName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getCurrentUserId());
        this.sysUserService.saveUser(user);
        return setSuccessModelMap();
    }
    
    /**
     * 分页查询
     * 
     * @param sysUser
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public ResponseEntity<ModelMap> list(SysUser sysUser)
    {
        PageInfo<SysUser> pageInfo = this.sysUserService.selectList(ConvertRequestUtil.pageRequest(), sysUser);
        return setSuccessModelMap(pageInfo);
    }
    
    /**
     * 跳转用户编辑页面
     * 
     * @param userId
     * @param modelMap
     * @return
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap modelMap)
    {
        modelMap.put("user", this.sysUserService.queryById(userId));
        modelMap.put("roles", this.sysRoleService.selectRolesByUserId(userId));
        modelMap.put("posts", this.sysPostService.selectPostsByUserId(userId));
        return Constants.MODULE_SYS_USER_PREFIX + "edit";
    }
    
    /**
     * 修改保存用户
     * 
     * @param user
     * @return
     */
    @Log(module = Module.ROLE, value = "修改用户", type = LogType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/edit")
    @ResponseBody
    public ResponseEntity<ModelMap> editSave(SysUser user)
    {
        if (user.getId() != null && user.getId().longValue() == 1)
        {
            throw new BusinessException("管理员用户，不支持修改！");
        }
        return setSuccessModelMap(this.sysUserService.updateUser(user));
    }
    
    /**
     * 跳转用户重置密码页面
     * 
     * @param userId
     * @param modelMap
     * @return
     */
    @RequiresPermissions("system:user:resetPwd")
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap modelMap)
    {
        modelMap.put("user", this.sysUserService.queryById(userId));
        return Constants.MODULE_SYS_USER_PREFIX + "resetPwd";
    }
    
    /**
     * 保存密码操作
     * 
     * @param user
     * @return
     */
    @Log(module = Module.ROLE, value = "修改密码", type = LogType.UPDATE)
    @RequiresPermissions("system:user:resetPwd")
    @PostMapping("/resetPwd")
    @ResponseBody
    public ResponseEntity<ModelMap> resetPwdSave(SysUser user)
    {
        // 密码加密
        user.setSalt(EncryptUtils.randomSalt());
        user.setPassword(EncryptUtils.encryptPassword(user.getUserName(), user.getPassword(), user.getSalt()));
        this.sysUserService.update(user);
        return setSuccessModelMap();
    }
    
    /**
     * 删除用户 支持批量删除
     * 
     * @param ids
     * @return
     */
    @Log(module = Module.ROLE, value = "删除用户", type = LogType.DELETE)
    @RequiresPermissions("system:user:remove")
    @PostMapping("/remove")
    @ResponseBody
    public ResponseEntity<ModelMap> remove(String ids)
    {
        String[] idAttr = ids.split(SEG_CHAR);
        List<Long> list = Lists.newArrayList();
        for (String id : idAttr)
        {
            list.add(Long.valueOf(id));
        }
        // 逻辑删除
        this.sysUserService.deleteUsers(list, ShiroUtils.getCurrentUserId());
        return setSuccessModelMap();
    }
    
    /**
     * 校验用户名是否重复
     * 
     * @param user
     * @return
     */
    @PostMapping("/checkUserNameUnique")
    @ResponseBody
    public String checkUserNameUnique(SysUser user)
    {
        return String.valueOf(this.sysUserService.countByUserName(user));
    }
    
    /**
     * 校验邮箱是否重复
     * 
     * @param user
     * @return
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user)
    {
        return this.sysUserService.countByEmail(user);
    }
    
    /**
     * 校验邮箱是否重复
     * 
     * @param user
     * @return
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user)
    {
        return this.sysUserService.countByPhone(user);
    }
    
}
